import logging
import time
import sys
import signal
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger("services")

# 导入消息服务
from app.services.message_service import message_service

class ServiceManager:
    """服务管理器，管理所有后台服务"""
    
    def __init__(self):
        """初始化服务管理器"""
        self.running = False
        # 注册信号处理器
        signal.signal(signal.SIGINT, self.handle_signal)
        signal.signal(signal.SIGTERM, self.handle_signal)
    
    def start(self):
        """启动所有服务"""
        self.running = True
        logger.info("Starting services...")
        
        # 启动消息服务
        message_service.start()
        
        logger.info("All services started")
        
        # 保持运行，直到收到停止信号
        try:
            while self.running:
                time.sleep(1)
        except Exception as e:
            logger.error(f"Error in service manager: {e}")
        finally:
            self.stop()
    
    def stop(self):
        """停止所有服务"""
        self.running = False
        logger.info("Stopping services...")
        
        # 停止消息服务
        message_service.stop()
        
        logger.info("All services stopped")
    
    def handle_signal(self, sig, frame):
        """处理信号"""
        logger.info(f"Received signal {sig}")
        self.stop()
        sys.exit(0)

if __name__ == "__main__":
    service_manager = ServiceManager()
    service_manager.start() 